<?php

/**
 * session 相关工具
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-02
 */

namespace fw\tool;

use fw\base\Instance;

class Session
{
    use Instance;

    public function __construct()
    {
        (!session_id()) && session_start();
    }

    public function destroy()
    {
        session_unset();
        session_destroy();
        $_SESSION = [];
    }

    public function delete($name)
    {
        if (strpos($name, '.') !== false) {
            list($k1, $k2) = explode('.', $name);

            unset($_SESSION[$k1][$k2]);
        } else {
            unset($_SESSION[$name]);
        }
    }

    public function set($name, $val)
    {
        if (strpos($name, '.') !== false) {
            list($k1, $k2) = explode('.', $name);

            $_SESSION[$k1][$k2] = $val;
        } else {
            $_SESSION[$name] = $val;
        }
    }

    public function get($name)
    {
        if (strpos($name, '.') !== false) {
            list($k1, $k2) = explode('.', $name);

            return isset($_SESSION[$k1][$k2]) ? $_SESSION[$k1][$k2] : null;
        } else {

            return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
        }
    }

    public function has($name)
    {
        if (strpos($name, '.') !== false) {
            list($k1, $k2) = explode('.', $name);

            return isset($_SESSION[$k1][$k2]) ? true : false;
        } else {

            return isset($_SESSION[$name]) ? true : false;
        }
    }
}
